package com.zpark.cloud.alibaba.service.impl;

import com.zpark.cloud.alibaba.entity.Storage;
import com.zpark.cloud.alibaba.mapper.IStorageMapper;
import com.zpark.cloud.alibaba.service.IStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 库存业务层接口实现类
 */
@Service
@Slf4j
public class StorageServiceImpl implements IStorageService {

    @Autowired
    private IStorageMapper storageMapper;

    /**
     * 减少库存
     * @param pid 商品id
     * @param count 下单的数量
     * @return
     */
    @Override
    public Integer decreaseStorage(Long pid, Integer count) {

        log.info("------->storage-service中扣减库存开始");
        log.info("------->storage-service 开始查询商品是否存在");
        // 根据商品id查询库存数据
        Storage storage = storageMapper.selectByProductId(pid);

        // 判断剩余库存量是否大于下单的数量，如果库存量小于下单量，提示库存不足
        if (storage == null || storage.getResidue().intValue() < count.intValue()) {
            log.info("------->storage-service 库存不足，开始回滚！");
            throw new RuntimeException("库存不足，修改库存失败");
        }
        // 库存充足，修改库存
        Storage changeStorage = new Storage();
        // 设置属性值
        changeStorage.setId(storage.getId());
        changeStorage.setProductId(pid);
        changeStorage.setTotal(storage.getTotal());
        changeStorage.setUsed(storage.getUsed() + count);
        changeStorage.setResidue(storage.getResidue() - count);

        // 调用持久层方法执行修改库存
        int row = storageMapper.updateByPrimaryKey(changeStorage);
        // 判断修改库存是否成功
        if (row <= 0) {
            log.info("------->storage-service 修改库存失败，开始回滚！");
            throw new RuntimeException("修改库存失败，原因未知");
        }
        log.info("------->storage-service 扣减库存成功");

        return row;
    }
}
